package org.hashdb.client.console.completer;

import jline.console.completer.Completer;
import org.hashdb.client.util.Strings;

import java.util.List;

/**
 * Date: 2024/1/11 21:32
 *
 * @author huanyuMake-pecdle
 * @version 0.0.1
 */
public class ConsumerKeywordAggregateCompleter implements Completer, RemoteCompleter {
    @Override
    public int complete(String buffer, int cursor, List<CharSequence> candidates) {
        String input = Strings.trimRight(buffer);
        int pipeIndex = input.lastIndexOf('|');
        if (pipeIndex == -1) {
            return -1;
        }
        String fragment = input.substring(pipeIndex).trim();
        String[] tokens = fragment.split(" ");
        if (tokens.length == 0) {
            candidates.addAll(ConsumerKeyword.names);
            return cursor;
        }
        if (tokens.length == 1) {
            boolean matched = false;
            String token = tokens[0].toUpperCase();
            for (ConsumerKeyword keyword : ConsumerKeyword.values()) {
                if (keyword.name().startsWith(token)) {
                    candidates.add(keyword.name());
                    matched = true;
                }
            }
            if (matched) {
                return cursor;
            } else {
                return -1;
            }
        }
        ConsumerKeyword matched = null;
        String token = tokens[0].toUpperCase();
        for (ConsumerKeyword keyword : ConsumerKeyword.values()) {
            if (keyword.name().startsWith(token)) {
                matched = keyword;
            }
        }
        if (matched == null) {
            return -1;
        }
        return matched.complete(tokens, cursor, candidates);
    }
}
